package com.pachong.android.framework.httprequest.volleyadaptee;

import android.text.TextUtils;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.pachong.android.framework.httprequest.HttpRequest;
import com.pachong.android.frameworkbase.utils.SLog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

/**
 * Http Request Helper
 *
 * @Author: pv
 * @E-mail: pengveivei@sina.cn
 * @CreateDate: 2016/7/30 11:41
 * @Version: 1.0.0
 */
public class ResponseHelper {

    /**
     * response 解析出来的string不能为非json格式的字符串，否则走失败分支
     * @param response
     * @return
     */
    public static Response<JSONObject> parseNetworkResponse2JSONObject(NetworkResponse response) {
        try {
            JSONObject jobj;
            String jsonString = parseString(response);
            if (TextUtils.isEmpty(jsonString)) {
                jobj = null;
            } else {
                jobj = new JSONObject(jsonString);
            }
            return Response.success(jobj, HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException var3) {
            return Response.error(new ParseError(var3));
        } catch (JSONException var4) {
            return Response.error(new ParseError(var4));
        }
    }


    public static Response<String> parseNetworkResponse2String(NetworkResponse response) {
        try {
            String jsonString = parseString(response);
            return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException var3) {
            return Response.error(new ParseError(var3));
        }
    }



    /**
     * 返回的string 不可以为null
     * @param response
     * @return could not be null
     * @throws UnsupportedEncodingException
     */
    private static String parseString(NetworkResponse response) throws UnsupportedEncodingException {
        String retStr;
        if (response.data == null || response.data.length <= 0) {
            // 返回值为空的时候volly走ErrorResponse回调
            retStr = "";
        } else {
            // je = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            // 将编码写死成UTF-8, 原先是要根据服务器header中的编码来自动编码
            retStr = new String(response.data, "utf-8");
        }

        SLog.e(HttpRequest.TAG, "ResponseHelper: parseNetworkResponse == " + retStr);
        return retStr;
    }


}
